package starter;

import java.util.LinkedList;

import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;


import ggt.Koordinator;
import ggt.StarterHelper;
import ggt.StarterPOA;
import ggt.StarterPackage.exInvalidCount;


public class StarterImpl extends StarterPOA {
	private String name;
	private Koordinator koor;
	private ORB orb;
	private LinkedList<ProzessImpl> prozesse;
	
	@SuppressWarnings("unused")
	private StarterImpl(){};
	
	public StarterImpl(String name, Koordinator koor, ORB orb){
		this.name = name;
		this.koor = koor;
		this.orb = orb;
		
		prozesse = new LinkedList<ProzessImpl>();
		// Bei dem Koordinator anmelden
		POA rootPoa;
		try {
			rootPoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootPoa.the_POAManager().activate();
			koor.aktiviereStarter(StarterHelper.narrow(rootPoa.servant_to_reference(this)), name);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public String name() {
		return this.name;
	}

	@Override
	public void erstelleProzesse(int anzahl) throws exInvalidCount {
		if(anzahl > 0 ){
			for(int i = 0; i < anzahl; i++){
				ProzessImpl p = new ProzessImpl(this.name + i, orb, koor);
				this.prozesse.add(p);
				Thread t = new Thread(p);
				t.start();
			}
		} else {
			throw new exInvalidCount("Anzahl muss groesser als 0 sein."); 
		}
	}

	@Override
	public void quit() {
		POA rootPoa;
		// Bei dem Koordinator abmelden
		try {
			rootPoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootPoa.the_POAManager().activate();
			koor.entferneStarter(StarterHelper.narrow(rootPoa.servant_to_reference(this)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//Alle Prozesse dieses Starters beenden
		while (prozesse.isEmpty()){
			prozesse.pop().quit(name);
		}
		orb.shutdown(true);
	}

}
